package index

import (
	"fmt"
	"im/internal/common"
	"im/internal/model"
	"im/pkg/databases"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	if c.Request.Method == "POST" {
		token := c.PostForm("token")
		user, err := common.GetUserByToken(token)
		if err != nil {
			c.HTML(http.StatusOK, "login.tmpl", gin.H{
				"error": fmt.Sprintf("登录失败: %s", err.Error()),
				"token": token,
			})
			return
		}
		if user != nil {
			c.Set("username", user.Username)
			c.Set("token", token)
			c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("/?token=%s", token))
			return
		}
	}
	c.HTML(200, "login.tmpl", gin.H{})
}

// AuthLogin 通过账号密码登录
func AuthLogin(c *gin.Context) {
	if c.Request.Method == "POST" {
		username := c.PostForm("username")
		password := c.PostForm("password")
		// 参数验证
		if username == "" || password == "" {
			c.HTML(http.StatusBadRequest, "auth-login.tmpl", gin.H{
				"error": "用户名和密码不能为空",
			})
			return
		}
		// 查询用户
		var user model.User
		result := databases.GetGorm().Where("user_id = ? AND status = ?", username, "normal").First(&user)

		// 检查查询结果
		if result.Error != nil {
			c.HTML(http.StatusUnauthorized, "auth-login.tmpl", gin.H{
				"error": "用户不存在或已被禁用",
			})
			return
		}
		//验证密码
		if common.GetEncryptPassword(password, user.Salt) != user.Password {
			c.HTML(http.StatusUnauthorized, "auth-login.tmpl", gin.H{
				"error": "密码错误",
			})
			return
		}
		return
	}
	c.HTML(200, "auth-login.tmpl", gin.H{})
}
